import io

import xlwt
from django.db.models import Q
from django.http import JsonResponse, HttpResponse
from django.shortcuts import redirect
from django.utils import timezone
from rest_framework.generics import ListAPIView
from rest_framework.pagination import PageNumberPagination

from search.models import Record
from search.serializers import RecordSerializer


def show_index(request):
    return redirect('/static/html/index.html')


class CustomizedPagination(PageNumberPagination):
    """自定义分页类"""
    page_size_query_param = 'size'
    max_page_size = 50


class RecordView(ListAPIView):
    """违章记录视图类"""
    serializer_class = RecordSerializer
    pagination_class = CustomizedPagination

    def get_queryset(self):
        queryset = Record.objects.filter(is_deleted=False)\
                .order_by('-makedate').select_related('car')\
                .defer('is_deleted', 'deleted_time', 'updated_time')
        keyword = self.request.GET.get('keyword')
        if keyword:
            queryset = queryset.filter(
                Q(car__owner__contains=keyword) | Q(car__carno__startswith=keyword)
            )
        return queryset


def handle_record(request):
    try:
        rno = int(request.GET.get('rno'))
        record = Record.objects.get(no=rno)
        if not record.dealt:
            record.dealt = True
            record.updated_time = timezone.now()
            record.save()
        data = {'code': 10000, 'message': '受理成功'}
    except (ValueError, Record.DoesNotExist):
        data = {'code': 10001, 'message': '受理失败'}
    return JsonResponse(data)


def delete_record(request):
    try:
        rno = int(request.GET.get('rno'))
        record = Record.objects.get(no=rno)
        if record.dealt:
            if not record.is_deleted:
                record.is_deleted = True
                record.deleted_time = timezone.now()
                record.save()
            data = {'code': 20000, 'message': '删除成功'}
        else:
            data = {'code': 20001, 'message': '不能删除未受理的记录'}
    except (ValueError, Record.DoesNotExist):
        data = {'code': 20002, 'message': '删除失败'}
    return JsonResponse(data)


def export_excel(request):
    wb = xlwt.Workbook()
    sheet = wb.add_sheet('违章记录表')
    titles = ('编号', '车牌号', '车主姓名', '违章原因', '违章日期', '处罚方式', '已受理')
    for col, title in enumerate(titles):
        sheet.write(0, col, title)
    records = Record.objects.filter(is_deleted=False)\
        .select_related('car')\
        .defer('is_deleted', 'deleted_time', 'updated_time')
    for row, record in enumerate(records):
        sheet.write(row + 1, 0, record.no)
        sheet.write(row + 1, 1, record.car.carno)
        sheet.write(row + 1, 2, record.car.owner)
        sheet.write(row + 1, 3, record.reason)
        sheet.write(row + 1, 4, record.makedate.strftime('%Y年%m月%d日'))
        sheet.write(row + 1, 5, record.punish)
        sheet.write(row + 1, 6, '是' if record.dealt else '否')
    buffer = io.BytesIO()
    wb.save(buffer)
    resp = HttpResponse(buffer.getvalue(), content_type='application/vnd.ms-excel')
    resp['content-disposition'] = 'attachment; filename="records.xls"'
    return resp
